<template>
    <div class="backtop" v-show="touchBottom">
        <div class="backtop-img" @click="smoothscroll()">
            <img class="full" src="https://m.mi.com/static/img/top.451d650ecd.png">
        </div>
    </div>
</template>

<script>

import { mapState} from 'vuex';

import {setdebounce} from "@/utils/lodash.js";

export default {
    name: 'Backtop',
    props:{
        targetEl:String
    },
    data() {
        return {
            el:null,
            touchBottom:0
        }
    },
    mounted() {
        this.el = document.querySelector(this.targetEl);
        if(!this.el) {
            return;
        }
        let bebounce = setdebounce(this.isTouch,100);
        this.el.addEventListener('scroll',bebounce);
    },
    computed: {
        ...mapState(['navIndex'])
    },
    methods:{
        show() {
            this.touchBottom = 1;
        },
        hide() {
            this.touchBottom = 0;
        },
        
        isTouch() {
            let h = this.el.scrollTop;
            if(h > 468) {
                this.touchBottom = 1;
            } else {
                this.touchBottom = 0;
            }
        },
        gotop() {
            this.el.scrollTo(0,0);
        },
        smoothscroll() {
            var currentScroll = this.el.scrollTop;
            if (currentScroll > 0) {
                window.requestAnimationFrame(this.smoothscroll);
                this.el.scrollTo(0, currentScroll - (currentScroll / 5));
            }
         }
    },
    watch: {
        navIndex() {
           this.gotop();
        }
    }
    
}
</script>

<style lang="stylus">
.backtop
    position fixed
    right 20px;
    bottom 80px;
    .backtop-img
        width 40.29px;
        height 40.29px;
</style>